from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from app.config.database_config import PgManager
from app.services.report_service import ReportService

router = APIRouter(prefix="/reports", tags=["reports"])

def get_report_service(db: Session = Depends(PgManager.get_db_static)) -> ReportService:
    return ReportService(db)

@router.get("/flight-load-rate")
def get_flight_load_rate(
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    service: ReportService = Depends(get_report_service)
):
    """获取航班载客率统计"""
    return service.get_flight_load_rate_stats(start_date, end_date)

@router.get("/revenue")
def get_revenue_stats(
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    group_by: str = Query("flight", regex="^(flight|date)$", description="分组方式"),
    service: ReportService = Depends(get_report_service)
):
    """获取收入统计"""
    return service.get_revenue_stats(start_date, end_date, group_by)

@router.get("/popular-routes")
def get_popular_routes(
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    limit: int = Query(10, ge=1, le=100, description="返回记录数"),
    service: ReportService = Depends(get_report_service)
):
    """获取热门航线分析"""
    return service.get_popular_routes(start_date, end_date, limit)

@router.get("/daily-trend")
def get_daily_booking_trend(
    days: int = Query(30, ge=1, le=365, description="天数"),
    service: ReportService = Depends(get_report_service)
):
    """获取每日预订趋势"""
    return service.get_daily_booking_trend(days)

@router.get("/monthly-summary")
def get_monthly_revenue_summary(
    months: int = Query(12, ge=1, le=60, description="月份数"),
    service: ReportService = Depends(get_report_service)
):
    """获取月度收入汇总"""
    return service.get_monthly_revenue_summary(months)

@router.get("/dashboard")
def get_dashboard_stats(
    service: ReportService = Depends(get_report_service)
):
    """获取仪表盘统计数据"""
    from app.services.booking_service import BookingService
    booking_service = BookingService(service.db)
    
    booking_stats = booking_service.get_booking_stats()
    popular_routes = service.get_popular_routes(limit=5)
    daily_trend = service.get_daily_booking_trend(days=7)
    
    return {
        "booking_stats": booking_stats,
        "popular_routes": popular_routes,
        "daily_trend": daily_trend
    }